const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { authMiddleware } = require('../middleware/auth');
const CODE = require('../constants/code');
const { logOperation } = require('../utils/log');

// 分配开发者到模块
router.post('/assign', authMiddleware, async (req, res) => {
    try {
        const { 
            moduleId,      // 模块ID
            userId,        // 被分配的用户ID
            role = 'developer', // 角色，默认为开发者
            estimatedHours // 预估工作小时数
        } = req.body;

        // 检查模块是否存在
        const [modules] = await pool.execute(
            'SELECT * FROM modules WHERE id = ?',
            [moduleId]
        );

        if (modules.length === 0) {
            return res.json({
                code: CODE.NOT_FOUND,
                message: '模块不存在'
            });
        }

        // 检查用户是否存在
        const [users] = await pool.execute(
            'SELECT * FROM users WHERE id = ?',
            [userId]
        );

        if (users.length === 0) {
            return res.json({
                code: CODE.NOT_FOUND,
                message: '用户不存在'
            });
        }

        // 插入或更新模块分配
        const [result] = await pool.execute(
            `INSERT INTO module_assignments 
            (module_id, user_id, role, estimated_hours) 
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE 
            role = VALUES(role), 
            estimated_hours = VALUES(estimated_hours)`,
            [moduleId, userId, role, estimatedHours]
        );

        // 记录操作日志
        await logOperation(
            {
                userId: req.user.userId,
                type: 'create',
                module: '模块分配',
                details: `分配模块 ${moduleId} 到用户 ${userId}`,
                ipAddress: req.ip,
                userAgent: req.headers['user-agent']
            }
        );

        res.json({
            code: CODE.SUCCESS,
            message: '模块分配成功',
            data: { assignmentId: result.insertId }
        });
    } catch (error) {
        console.error('模块分配错误:', error);
        res.status(500).json({
            code: CODE.SERVER_ERROR,
            message: '服务器错误'
        });
    }
});

// 获取模块的所有分配
router.get('/list/:moduleId', authMiddleware, async (req, res) => {
    try {
        const { moduleId } = req.params;

        const [assignments] = await pool.execute(
            `SELECT 
                ma.id,
                ma.module_id,
                ma.user_id,
                u.real_name,
                u.username,
                ma.role,
                ma.status,
                ma.estimated_hours,
                ma.actual_hours,
                ma.assigned_date
            FROM module_assignments ma
            JOIN users u ON ma.user_id = u.id
            WHERE ma.module_id = ?
            ORDER BY ma.assigned_date DESC`,
            [moduleId]
        );

        res.json({
            code: CODE.SUCCESS,
            message: '获取模块分配成功',
            data: { assignments }
        });
    } catch (error) {
        console.error('获取模块分配错误:', error);
        res.status(500).json({
            code: CODE.SERVER_ERROR,
            message: '服务器错误'
        });
    }
});

// 更新模块分配状态
router.put('/update-status', authMiddleware, async (req, res) => {
    try {
        const { 
            assignmentId, 
            status,
            actualHours 
        } = req.body;

        const [result] = await pool.execute(
            `UPDATE module_assignments 
            SET status = ?, 
                actual_hours = ? 
            WHERE id = ?`,
            [status, actualHours, assignmentId]
        );

        if (result.affectedRows === 0) {
            return res.json({
                code: CODE.NOT_FOUND,
                message: '模块分配记录不存在'
            });
        }

        // 记录操作日志
        await logOperation(
            {
                userId: req.user.userId,
                type: 'update',
                module: '模块分配',
                details: `更新模块分配 ${assignmentId} 状态为 ${status}`,
                ipAddress: req.ip,
                userAgent: req.headers['user-agent']
            }
            // req.user.userId,
            // 'update',
            // '模块分配',
            // `更新模块分配 ${assignmentId} 状态为 ${status}`,
            // req.ip,
            // req.headers['user-agent']
        );

        res.json({
            code: CODE.SUCCESS,
            message: '更新模块分配状态成功'
        });
    } catch (error) {
        console.error('更新模块分配状态错误:', error);
        res.status(500).json({
            code: CODE.SERVER_ERROR,
            message: '服务器错误'
        });
    }
});

module.exports = router;